package com.xinyue.game.dataconfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.springframework.util.ObjectUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Set;

/**
 * @Author 王广帅
 * @Date 2021/5/9 18:48
 */

public class GameDataConfigContext {

    private GameDataConfigService gameDataConfigService;

    public GameDataConfigContext(GameDataConfigService gameDataConfigService) {
        this.gameDataConfigService = gameDataConfigService;
    }

    /**
     * 开始加载配置数据
     *
     * @param configDir              配置文件目录
     * @param dataConfigClassPackage 配置文件类类所在的包路径，比如com.xinyue.dataconfig
     */
    public void startReload(String configDir, String dataConfigClassPackage) throws Exception {
        //因为要获取所有Object的子类，所以这里必须添加SubTypesScanner 为false，否则会报错
        Reflections reflections = new Reflections(dataConfigClassPackage, new SubTypesScanner(false));
        Set<Class<?>> allClass = reflections.getSubTypesOf(Object.class);
        for (Class<?> clazz : allClass) {
            readConfigFile(configDir, clazz);
        }
    }

    private String getConfigFileName(Class<?> clazz) {
        String name = clazz.getSimpleName();
        String fileName = name + ".json";
        return fileName;
    }

    private void readConfigFile(String configDir, Class<?> clazz) throws Exception {
        String fileName = getConfigFileName(clazz);
        File configFile = new File(configDir, fileName);
        List<String> configDataList = FileUtils.readLines(configFile, StandardCharsets.UTF_8);
        JSONObject jsonObject;
        String id;
        Object data;
        for (String configData : configDataList) {
            if (ObjectUtils.isEmpty(configData)) {
                continue;
            }
            jsonObject = JSON.parseObject(configData);
            //这个id是和工具那边约定的，配置表里面也约定，第一列名字必须是id
            id = jsonObject.getString("id");
            data = jsonObject.toJavaObject(clazz);
            gameDataConfigService.addDataConfig(clazz, id, data);
        }
    }

}
